function [sampleTotals] = interExaminTime(varargin)

% To record the rating change time intervals if there's a jump between consecutive ratings 

%Parse parameter-value pairs
parser = inputParser;
parser.addRequired('data',@dataCheck);
parser.addParamValue('labels',...
   {'AAA','AA','A','BBB','BB','B','CCC','D'},@labelsCheck);
parser.addParamValue('startDate',0,@startDateCheck);
parser.addParamValue('endDate',0,@endDateCheck);
parser.addParamValue('algorithm','duration',@algorithmCheck);

parser.parse(varargin{:});

data = parser.Results.data;
labels = parser.Results.labels;
startDate = datenum(parser.Results.startDate);
endDate = datenum(parser.Results.endDate);


idStart = [];
numDate = [];
numRating = [];
if isstruct(data)
    idStart = data.idStart;
    numDate = data.numericDates;
    numRating = data.numericRatings;
    labels = data.ratingsLabels;
elseif iscell(data)    
    prepData = transprobprep(data,'labels',labels);
    idStart = prepData.idStart;
    numDate = prepData.numericDates;
    numRating = prepData.numericRatings;
end


nRatings = length(labels);
if startDate == 0
   startDate = min(numDate);
end
if endDate == 0
   endDate = max(numDate);
end

% Get totals per ID
   idTotals = getIdTotalsDur(numDate,numRating,idStart,startDate,...
      endDate,nRatings);
% Get sample totals
sampleTotals = getSampleTotals(idTotals,numDate,idStart);

  % Aggregate totals for the whole sample
function sampleTotals = getSampleTotals(totals,numDate,idStart)

totalsVec = zeros(size(totals(1).totalsVec));
totalsMat = zeros(size(totals(1).totalsMat));
totalsRec = zeros(size(numDate));

for k = 1:length(totals)
   totalsVec = totalsVec + totals(k).totalsVec;
   totalsMat = totalsMat + totals(k).totalsMat;
   totalsRec(idStart(k):idStart(k)+length(totals(k).totalsRec)-1) = totals(k).totalsRec;
end
totalsRec = totalsRec(totalsRec>0);
sampleTotals = struct('totalsVec',totalsVec,...
                      'totalsMat',totalsMat,...
                      'totalsRec',totalsRec);
 

 
%-------------------------------------------------------------------------
% Get totals per ID, duration method
function idTotals = getIdTotalsDur(numDate,numRating,idStart,startDate,...
   endDate,nRatings)

nIDs = length(idStart)-1;
idTotals(nIDs,1) = struct('totalsVec',[],'totalsMat',[],'totalsRec',[]);

% Introduce an artificial 'NaN' state - time window can be larger than some
% companies' migration history
nRtgsNaN = nRatings+1;

for k = 1:nIDs

   totalsVec = zeros(1,nRtgsNaN);
   totalsMat = zeros(nRtgsNaN,nRtgsNaN);
   totalsRec = zeros(idStart(k+1),1);

   [date,rating] = getRatingsLocal(k,numDate,numRating,idStart,...
                                   startDate,endDate);
   rating(isnan(rating)) = nRtgsNaN;
   temp = 0;
   % Info at start time
   prevDate = date(1);
   prevRtg = rating(1);

   for t = 2:length(date)
      % Get info on latest transition
      currDate = date(t);
      currRtg = rating(t);
      
      elapsedTime = yearFractionLocal(prevDate,currDate);
      % Update total time spent in previous rating
      %totalsVec(prevRtg) = totalsVec(prevRtg) + elapsedTime;
      temp = temp + elapsedTime;
      
      if (prevRtg ~= currRtg) %&& (prevRtg ~= 9)%? why ~=9
          totalsRec(t-1,1) = temp;
          totalsVec(prevRtg) = totalsVec(prevRtg) + temp;%useless
          temp = 0;
      end
      
      if(prevRtg ~= currRtg)
          % Update counts according to latest transition
          totalsMat(prevRtg,currRtg) = totalsMat(prevRtg,currRtg) + 1; %useless
      end
      % Shift current info
      prevDate = currDate;
      prevRtg = currRtg;
   end
   
   idTotals(k).totalsVec = sparse(totalsVec(1:nRatings));
   idTotals(k).totalsMat = sparse(totalsMat(1:nRatings,1:nRatings));
   idTotals(k).totalsRec = totalsRec(totalsRec>0);
   
end



%-------------------------------------------------------------------------
% Get ratings information, within a given time window, for a given index
function [date,rating] = getRatingsLocal(ind,numDate,numRating,idStart,...
   startDate,endDate)

ind1 = idStart(ind);
ind2 = idStart(ind+1)-1;

% Insert time-window limit dates and sort by date
dTemp = [startDate;numDate(ind1:ind2);endDate];
rTemp = [NaN;numRating(ind1:ind2);NaN];
[dTemp,iTemp] = sort(dTemp);
rTemp = rTemp(iTemp);

% Take care of rating information on the boundaries
i1 = find(iTemp==1);
if (dTemp(i1)==dTemp(i1+1))
   i1 = i1 + 1;
elseif (i1>1)
   rTemp(i1) = rTemp(i1-1);
end
n = length(dTemp);
i2 = find(iTemp==n);
if (dTemp(i2)==dTemp(i2-1))
   i2 = i2 - 1;
else
   rTemp(i2) = rTemp(i2-1);
end

date = dTemp(i1:i2);
rating = rTemp(i1:i2);


%-------------------------------------------------------------------------
% Get year fraction, uses different conventions than yearfrac
function frac = yearFractionLocal(date1,date2)

year2 = year(date2);
year1 = year(date1);
month1 = month(date1);
day1 = day(date1);

dayDiffYr2 = date2-datenum(year2,month1,day1);
daysInYr2 = daysact(datenum(year2,1,1)-1,datenum(year2,12,31));
frac = year2-year1+dayDiffYr2./daysInYr2;

%-------------------------------------------------------------------------
% Check value of 'data' parameter
function OK = dataCheck(data)

if isstruct(data)
   if ~isfield(data,'idStart')...
         || ~isfield(data,'numericDates')...
         || ~isfield(data,'numericRatings')...
         || ~isfield(data,'ratingsLabels')
      error(message('finance:transprob:StructDataInvalid'))
   end
elseif ~iscell(data) || size(data,2)~=3
   error(message('finance:transprob:DataInvalid'))
end
OK = true;

%-------------------------------------------------------------------------
% Check value of 'labels' parameter
function OK = labelsCheck(labels)

if ~iscell(labels)
   error(message('finance:transprob:LabelsNonCell'))
elseif ischar(labels{1,1})
   if sum(cellfun(@ischar,labels)) < length(labels)
      error(message('finance:transprob:LabelsMixedTypes'))
   end
elseif isnumeric(labels{1,1})
   if sum(cellfun(@isnumeric,labels)) < length(labels)
      error(message('finance:transprob:LabelsMixedTypes'))
   end
end
OK = true;

%-------------------------------------------------------------------------
% Check value of 'startDate' parameter
function OK = startDateCheck(startDate)

try
   datenum(startDate);
catch e
   error(message('finance:transprob:StartDateInvalid'))
end
OK = true;

%-------------------------------------------------------------------------
% Check value of 'endDate' parameter
function OK = endDateCheck(endDate)

try
   datenum(endDate);
catch e
   error(message('finance:transprob:EndDateInvalid'))
end
OK = true;


